package com.founder.android.http;

import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;

/**
 * HTTP异步请求
 * @author chen_weihua
 *
 */
public class AsynchronousSender extends Thread {
	
    //private static final String CHARSET = HTTP.UTF_8;
    /* 连接超时 */
    private static final int CONNECTION_TIME_OUT = 1*60*1000;
    /* 请求超时 */
    private static final int REQUEST_TIME_OUT = 2*60*1000;
    
    private static HttpClient httpClient;
	
	private HttpUriRequest request;
	
	private Handler handler;
	
	private CallbackWrapper wrapper;
	
	public AsynchronousSender(Context context, HttpUriRequest request,
			Handler handler, CallbackWrapper wrapper) {
		this.request = request;
		this.handler = handler;
		this.wrapper = wrapper;
		if (httpClient == null) {
			httpClient = getHttpClient(context);
		}
	}
 
	/**
	 * 异步执行请求
	 */
	public void run() {
		final HttpResponse response;
		try {
			synchronized (httpClient) {
				response = httpClient.execute(request);
			}
			wrapper.setResponse(response);
			HttpEntity entity = response.getEntity();
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode != HttpStatus.SC_OK) {
				wrapper.setError(new Exception("Service Status Code: " + statusCode + "!"));
			} else if (entity == null) {
				wrapper.setError(new Exception("Respose Content is NULL!"));
			} else {
				try {
					wrapper.setResult();
					wrapper.setSuccess(true);
				} catch (Exception e) {
					wrapper.setError(e);
				}
			}
		} catch (Exception e) {
			wrapper.setError(e);
		}
		handler.post(wrapper);
	}
    
    private HttpClient getHttpClient(Context context) {
        if (null == httpClient) {
            HttpParams params = new BasicHttpParams();
            // 设置一些基本参数
            //HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
            //HttpProtocolParams.setContentCharset(params, CHARSET);
            //HttpProtocolParams.setUseExpectContinue(params, true);
            //HttpProtocolParams.setUserAgent(params, "Mozilla/5.0(Linux;U;Android 2.2.1;en-us;Nexus One Build.FRG83) AppleWebKit/553.1(KHTML,like Gecko) Version/4.0 Mobile Safari/533.1");
            // 超时设置
            //ConnManagerParams.setTimeout(params, 1000);//从连接池中取连接的超时时间
            HttpConnectionParams.setConnectionTimeout(params, CONNECTION_TIME_OUT);
            HttpConnectionParams.setSoTimeout(params, REQUEST_TIME_OUT);
         
            // 设置我们的HttpClient支持HTTP和HTTPS两种模式
            SchemeRegistry schReg = new SchemeRegistry();
            schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
            schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

            // 使用线程安全的连接管理来创建HttpClient
            ClientConnectionManager conMgr = new ThreadSafeClientConnManager(params, schReg);
            httpClient = new DefaultHttpClient(conMgr, params);
            
            if (context != null) {
			    NetworkInfo networkInfo = ((ConnectivityManager) context
						.getSystemService(Context.CONNECTIVITY_SERVICE))
						.getActiveNetworkInfo();
				// 获取默认代理主机ip 及端口
				String host = android.net.Proxy.getDefaultHost();
				int port = android.net.Proxy.getDefaultPort();
				//Log.d("user proxy", "host:" + host + ", port:" + port);
				if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE && host != null && port != -1){
				    HttpHost proxy = new HttpHost(host, port);    
				    httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);   
				}
		    }
        }
        return httpClient;
    }

}
